﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ATTools.Services;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
using Orchard.Environment.Extensions;
using Orchard.Utility.Extensions;

namespace ATTools.Controllers
{
    [OrchardFeature("ATTools")]
    public class AdminController : Controller
    {
        private readonly ITranslationService _translationService;
        private readonly IContentManager _contentManager;

        public AdminController(ITranslationService translationService, IContentManager contentManager)
        {
            _translationService = translationService;
            _contentManager = contentManager;

        }

        public ActionResult Edit(int id)
        {
            //Translation of the bodytext
            string translateTo = this.HttpContext.Request.Params["to"];
            var contentItem = _contentManager.Get(id, VersionOptions.Latest);
            
            BodyPart body = contentItem.As<BodyPart>();
            var text = HttpUtility.HtmlDecode(body.Text);
            
            //Auto detect the language of the bodytext
            string detectedLanguage = _translationService.DetectLanguages(new string[] { text.RemoveTags() }).First<string>();
            IEnumerable<string> translations = _translationService.Translate(new string[] { text }, detectedLanguage, translateTo, true);

            //Save the translated text as the new bodytext
            string translatedText = translations.First<string>();
            body.Text = translatedText;

            return this.Redirect(Request.UrlReferrer.AbsoluteUri);
        }

     
    }
}